
import axios from "axios";
import moment from "moment";
import crypto from "crypto";
import { json } from "stream/consumers";

const baseUrl = "https://api.qipiao.net";
const APPID = 'APP101303';
const entid = '101303';
const appSecret = 'R33mkS80T0qbe1J4eh2Bcn6QrJRbc313';

let token = '';
let token_expire_time = moment().unix();

const publicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5J4IT8QyMcqAXvWYD55N1rpRX5LxRail/Vt+slsFaSPOTGDONMqXil6dBswNPB4Du3Id8fgdjagcQsm/e5CpLXb1l+vf5/X2W8bQLVZnzhrbFl1lJErWYLrZQ6/IBwPlswHf7lYCYuThcToXKHRp/r7QHdMX6hp00Mcr2SGcqltdfgC9SMKnP8WjZnLP+m7BYtydvN2R5BiMnTf2i/8x/WQUM92KwbYGp8ISUfU2+PBcVw7kNaMngzElfWZTK0fvfj/nKGCWAN3Jx4b14djSQi1lKO56UD5J8oBGLw9nkwDjgTOqqeeSmPzU2Z+ILpECcsbFyVaLEvwSjBDfnx8PJQIDAQAB
-----END PUBLIC KEY-----`;

/**
 * 回调下行签名验证方法
 * @param {*} data 数据内容 
 * @param {*} signature 签名
 * @returns 
 */
function verifySignature(data, signature) {
    try {
        // 创建一个验证器
        const verifier = crypto.createVerify('SHA256');

        // 将数据传入验证器
        verifier.update(data, 'utf8');
        verifier.end();

        // 使用公钥和签名来验证数据
        const isVerified = verifier.verify(publicKey, signature, 'base64');
        return isVerified;
    } catch (error) {
        console.error('Error during verification:', error);
        return false;
    }
}

// 验证签名
//   const isSignatureValid = verifySignature('测试abc', 'PpOkZ5c/TGxGPP6wbpIu93PzMkB44vx/1ohfuNIeWNSbToPOnSeoq+1DJaJFpKUr3r++OtWBzLh7FJPULCVLxRpFo/Of6dH9JCcZZnXrOteIv/yDjCRF5Me19AF0JoJwhsB85t2SYyxDaYQl50munidyAlYSt6kxuj7NqZbltMzZWJHNm7E3SwVI+eP9Iyn9xWoUmR/Syra4ZQw+fG8ucHT3f8qyUmzy2rEH1yrD/bnZZyc3WaIVfmuudk1SSamjTkf0v8JQYrBWjVyXjJgrUhMlJvwx6CEwLU7Bm/dPXhOFql7iB0lkXYSNxqOUclhI7WaEUrtfBUGdXoejq6eQ1A==', publicKey);
//   console.log('Is signature valid?', isSignatureValid);
async function getToken() {
    if (moment().unix() < token_expire_time) {

        console.log("token未过期", moment.unix(token_expire_time).format('YYYY-MM-DD HH:mm:ss'), moment().format('YYYY-MM-DD HH:mm:ss'));
        return true;
        
    }
    
    console.log('获取token');
    let data = {
        entid,
        appSecret
    };
    let res = await qipiao_post("/api/oauth/token", data, false);
    console.log('获取token返回', res);
    if (res.code === 0) {
        token = res.data.access_token;
        token_expire_time = res.data.expires_at;
        console.log('token 到期时间', moment.unix(token_expire_time).format('YYYY-MM-DD HH:mm:ss'));
        return true;
    } else {
        console.warn(`奇票获取token失败 错误原因${res.message}`);
        return false;
    }
}

async function qipiao_post(path, param, needAuth = true) {
    let url = baseUrl + path;
    try {
        let res = null;
        if (needAuth) {
            if (!await getToken()) {
                return { code: -1, message: '获取token失败' };
            }
            res = await axios.post(url, param, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
        } else {
            res = await axios.post(url, param);
        }
        // console.log('qipiao_post.res', res.data);
        if (res.data.code !== 0) {
            console.warn(`奇票接口调用失败.请求地址:${url} 入参:${JSON.stringify(param)} 错误原因${res.data.message}`);
            return {  err: res.data.message };
        } else {
            console.log(`奇票接口调用成功.请求地址:${url} 入参:${JSON.stringify(param)} 返回结果:${JSON.stringify(res.data)}`);
        }
        return res.data;
    } catch (e) {
        console.warn(`奇票接口调用失败.请求地址:${url} 入参:${JSON.stringify(param)} 错误原因${e.message}`);
        return {  err: e.message };
    }
}
async function qipiao_get(path, param) {
    let url = baseUrl + path;
    if (param) {
        url += '?';
        for (let key in param) {
            url += `${key}=${param[key]}&`;
        }
        url = url.slice(0, -1);
    }
    console.log(url);
    try {
        let res = null;
        if (!await getToken()) {
            return { code: -1, message: '获取token失败' };
        }
        res = await axios.get(url, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        if (res.data.code !== 0) {
            console.warn(`奇票接口GET调用失败.请求地址:${url}  错误原因${res.data.message}`);
            return {  err: res.data.message };
        } else {
           // console.log(`奇票接口调用成功.请求地址:${url} 返回结果:${JSON.stringify(res.data)}`);
            return res.data;
        }
    } catch (e) {
        console.warn(`奇票接口调用失败.请求地址:${url} 错误原因${e.message}`);
        return {  err: e.message };
    }
}


// async function test() {
//     let url = `${baseUrl}/api/city/list`;
//     console.log(url);
//     let res = await qipiao_get(url);
//     console.log(res.data);
// }
// cityId {
//     cityId: '16',
//     name: '武汉',
//     pinYin: 'wuhan',
//     letter: 'W',
//     provinceId: '17',
//     provinceName: '湖北省'
//   }

async function test() {
// let data={
//     appId: APPID,
//     orderId: '20250214191900200082025',
//     cinemaCode:'42019981',
//     hallName:'6号厅',
//     movieCode:'00200082025',
//     seatNames:'6排4座',
//     sessionBeginTime:"2025-02-14T19:19:00",
//     originPrice: 46.9,
//     test:true,
//     orderPayMode:1,
//     pushUrl:'http://39.104.15.44:80/isp/notice/movie'
    
// }
// let res = await qipiao_post('/api/movie/create_order2',data);
// console.log(res);
// let data={
//     appId: APPID,
//     giftCardId: 'a0d438d8-c45e-ea11-8155-a7950ab505b7',
//     phone:"18971266199",
//     remark:"18971266199",
//     count:1,
//     // test:true,
//     pushUrl:'http://39.104.15.44:80/isp/notice/giftcard'
    
// }
// // let res = await qipiao_post('/api/gift_card/create_order',data);
// // console.log(res);
  

// let res = await qipiao_get('/api/gift_card/order_detail',{id:'d16b84b0-894b-47ef-0100-84855ce2720c'});
// console.log(res);
let data={
    "appId": APPID,//用自己企业的appId
    // "shopName": "大沙田",
    // "address": "方广场一二层良庆区大沙田开发区第十三小区（五象大道1号）鑫利华大厦商业裙楼一楼仙葫蓉茉大道东",
    "cityId": "16",
    //"cityCode": "00367",
    "shopId": "cddd3b88-79ec-49c0-a25e-4a6e016a9caf",
    // "shopCode": "NNG039",
    "eatType": 0,
    "phone": "18971266199",//用取餐人的手机号码
    "remark": "",
    "orderSn": "",
    "products": [
      {
        "productId": "12339225",
        "linkId": "",
        "quantity": 1,
        "nameCn": "香辣鸡翅(2块)",
        "imageUrl": "https://bucket.zxmall.com/goodsMge/999999_11134617_2641.png",
        "menuFlag": "P",
        "sellPrice": 11.2,//建议销售价（对应店铺菜单数据priceHead）
        "oPrice": 14,//市场价（对应店铺菜单数据price）
        "selected": []//肯德基商品目前都为单品，不需要调用商品详情，直接使用店铺菜单数据下单
      }
    ],
    "giftAmount": 0,//礼金功能未开放，传0
    "pushUrl":"http://39.104.15.44:80/isp/notice/food",//回调推送地址（如果有值，订单相关回调我方将推送到这个地址）
    "test":true
  }
    let res = await qipiao_post('/api/kfc/create_order',data);
    console.log('创建点餐订单返回',JSON.stringify(res),res);

  
}

    // test();
export { qipiao_post, qipiao_get,APPID };